<?php
namespace Home\Controller;

use Utuo\DistributionShopForeground;
use My\Model\DistributionShopOrderModel;
use Utuo\Region;
use My\Model\DistributionShopConfigModel;
use My\Model\WechatUserModel;
use My\Model\DistributionShopRedPacketModel;
use My\Model\DistributionShopJobTitleModel;
use My\Model\UserRole;
use My\Model\OrderModel;
use Utuo\DistributionShopDonate;
use Utuo\DistributionShopScore;
use Home\Logic\ScoreEventLogic;

class DisShopController extends DistributionShopForeground {
    
    // 价格搜索区间
    private $prices = array(
        '1-49' => array( name => '1-49', value => '1-49'),
        '50-59' => array( name => '50-59', value => '50-59',),
        '60-99' => array( name => '60-99', value => '60-99',),
        '100-199' => array( name =>'100-199', value => '100-199',),
        '200-299' => array( name =>'200-299', value => '200-299',),
        '300-399' => array( name =>'300-399', value => '300-399',),
        '400-599' =>  array( name =>'400-599', value => '400-599',),
        '600-799' => array( name =>'600-799', value => '600-799',),
        '800-' =>  array( name => '800以上', value => '800-',),
    );
	
    // 更换栏目
    private function setCategory( $category ) {
        $this->catId = $category['id'];
        $this->category = $category;
        $this->getCategory();
    }
    
    // 获取目录
    private function getCategory() {
        if ( !$this->category ) {
            $id = I('id', 0, 'intval');
            $map['id'] = $id;
            $map['cid'] = $this->sid;
            $map['status'] = 1;
            $map['is_deleted'] = 0;
            $this->category = M('DistributionShopCategory')->cache(true)->where($map)->find() or $this->catId = 0;
        }
        $this->setPageTitle($this->category['name'], $this->config['name']);
        $this->catId = $this->category['id']*1;
        $this->assign('category', $this->category);
        $this->assign('cat_id', $this->catId );
        return $this->category;
    }
    
    // 商品搜索
    private function search() {
        $category = $this->getCategory();
        $p = I("p", 1, "intval");
        $catId = $this->catId;
        $brandId = I('brands', 0, 'intval');
        $effId = I('efficiency', 0, 'intval');
        $keywords = I('keywords', '');
        $tag = I('tag', '');
        $isLow = I('is_low', -1, 'intval');
        $price = I('prices', 0);
        
        /* 排序 */
        $ord = I('ord', 0, "intval"); // 排序方式
        $sortStr = "sort asc";
        
        $pageSize = $this->getPageSize();
        $page = $this->getPage();
        $condition = array( 'a.cid' => $this->sid, 'a.is_deleted' => 0, '_string' => "a.status=1 or (a.status=0 and a.timing_shelves!=0)"  );
        $prices = $this->prices;
        if ( $price ) {
            list($min, $max) = explode('-', $price);
            $min*=1; $max*=1;
            if ( $min == $max ) {
                if ( $min != 0 ) {
                    $condition['price'] = array('eq', $min);
                }
            } elseif ( !$max and $min ) {
                $condition['price'] = array('egt', $min);
            } elseif( !$min and $max ) {
                $condition['price'] = array('elt', $max);
            } else {
                $condition['price'] = array(array('gt', $min), array('lt', $max), 'and') ;
            }
        }
        if ( $keywords ) {
            $condition['a.name'] = array('like', "%$keywords%");
            $this->setPageTitle( $keywords );
        }
        if( $catId ) {
            $condition['b.path'] = array("exp", " is not null and find_in_set($catId, b.path) ");
            $this->setPageTitle( $category['name'] );
        }
        if ( $brandId ) {
            $condition['a.brand'] = array("exp", " is not null and find_in_set($brandId, a.brand) ");
            $productBrand = M("CustomerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")->where("a.id=%d", $brandId)->field('a.id,case when a.name is not null then a.name when a.name is null then b.name end as name,a.brand')->find();
            $this->setPageTitle( $productBrand['name'] );
        }
        if ( $effId ) {
            $condition['a.efficiency'] = array("exp", " is not null and find_in_set($effId, a.efficiency) ");
            $productEfficiency = M("ProductEfficiency")->where("id=%d", $effId)->find();
            $this->setPageTitle( $productEfficiency['name'] );
        }
        if ( $isLow != -1 ) {
            $condition['a.is_low'] = ($isLow >=1 ? 1 : 0);
            $this->setPageTitle( '聚惠商品' );
        }
        if ( $tag ) {
            $condition['a.tag'] = array('eq', $tag);
        }
    
        $m = M("DistributionShopGoods a")->JOIN("__DISTRIBUTION_SHOP_CATEGORY__ b on a.cate_id=b.id", "LEFT")->where($condition);
        $n = clone $m;
        $list = $m->page($page)->limit($pageSize)->field('a.*')->order($sortStr)->select(); // ROUND(a.price/a.price_high*10, 1) as discount
        foreach ( $list as $k => &$v) {
            $v['discount'] = number_format(($v['price'])/$v['high_price']*10, 1);
            $images = unserialize($v['images']);
            $v['images'] = $images;
            $v['pic'] = $images[0];
        }
        $group = $n->field("GROUP_CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX(concat(b.path,',-'), ',', find_in_set($catId, concat(b.path,',-')) + 1), ',', -1)) as id,
            GROUP_CONCAT(a.brand) as brands, GROUP_CONCAT(a.efficiency) as efficiency, count(*) as count")->find();
    
        if( !empty($group['id']) ) {
            $group['id'] = M("DistributionShopCategory")->where(array('id' => array('in', $group['id'])))->field("id as value,name")->select();
            if ( $group['id'] ) {
                // 有子级
            } else { // 无子级
                $group['id'] = array();
            }
        } else {
            $group['id'] = array();
        }
        $catId and array_unshift($group['id'], array('value' => $category['id'], 'name' => $category['name'], 'selected' => 1 )); // 在查出的子级列表第一项加入当前选择的栏目
        $group['id'] = array_merge( array(array( 'value' => $category['pid']*1, 'name' => '全部分类', 'selected' => $catId==0 ? 1 : 0 ) ), $group['id'] );
        $menuSelected['id'] = $catId;
    
        if( !empty($group['brands']) ) {
            $group['brands'] = M("CustomerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")->where(array('a.id' => array('in', $group['brands'])))->field('a.id as value,case when a.name is not null then a.name when a.name is null then b.name end as name')->select();
            $group['brands'] or $group['brands'] =  array();
        } else {
            $group['brands'] =  array();
            $productBrand and $group['brands'][] = array('value' => $productBrand['id'], 'name' => $productBrand['name'], 'selected' => 1 );
        }
        $group['brands'] = array_merge(array(array('value' => 0, 'name' => '全部品牌')), $group['brands']);
        foreach ( $group['brands'] as &$v) {
            if ( $v['value'] == $brandId ) {
                $v['selected'] = 1;
                break;
            }
        }
        $menuSelected['brands'] = $brandId;
    
        if( !empty($group['efficiency']) ) {
            $group['efficiency'] = M("ProductEfficiency")->where(array('id' => array('in', $group['efficiency'])))->field("id as value,name")->select();
        } else {
            $group['efficiency'] = array();
            $productEfficiency and $group['efficiency'][] = array('value' => $productEfficiency['id'], 'name' => $productEfficiency['name'], 'selected' => 1 );
        }
        $group['efficiency'] = array_merge(array(array('value' => 0, 'name' => '全部功效')), $group['efficiency']);
        foreach ( $group['efficiency'] as &$v) {
            if ( $v['value'] == $effId ) {
                $v['selected'] = 1;
                break;
            }
        }
        $menuSelected['efficiency'] = $effId;
    
        if( $price and !array_key_exists($price, $prices) ) { // 自定义搜索价格
            $prices = array_merge(array( 0 => array( 'name' => $price, 'value' => 0, 'selected' => 1)), $prices);
        }
        $prices = array_merge(array( 0 => array( 'name' => '全部价格', 'value' => 0)), $prices);
        if( array_key_exists($price, $prices) ) {
            $prices[$price]['selected'] = 1;
        }
        $menuSelected['prices'] = $price;
    
        $group['prices'] = $prices;
        $rowCount = $group['count'];
        unset( $group['count'] );
    
        $menuSelected['keywords'] = $keywords;
    
        foreach ($list as &$v)
            $v['url'] = U('DisShop/show', array('sid'=>$this->cid, 'id' => $v['id']));
        
        return array(
            'totalRows' => $rowCount,
            'totalPages' => ceil($rowCount / $pageSize),
            'page' => $page,
            'data' => $list,
            'menu' => $group,
            'menuSelected' => $menuSelected,
        );
    }
    
	/**
	 * 初始化
	 */
	public function _init() {
		layout('disshop');
		$this->setModelName('DistributionShop');
		$this->setModelControllerName();
		if ( !in_array(ACTION_NAME, array('downCust','addBank','getCityPost','saveBank','withdrawPost','bankList','setDefaultBank','materialList','search','saveUser','getRecommendedDealerCount','getDistributionCount')) ) { // 排除不支持分享跳转的链接
			$this->setSupportRedirect(isset($_REQUEST['debug'])?false:true);
		}
	}
	
	/**
	 * 保存用户资料
	 */
	public function userInfoAction() {
	    $this->assign("user", $this->getUser());
	    $this->display();
	}
	
	/**
	 * 保存用户资料
	 */
	public function saveUserAction() {
	    $m =  M("WechatUser");
	    $user = $m->find($this->uid);
	    if ( $m->field("name,wechat,tel,qq")->create() ) {
	        if ( !$m->name or !$m->wechat or !$m->tel or !$m->qq ) {
	            $this->ajaxError("资料填写不完整");
	        } 
	        if( false !== $m->where("id=%d", $this->uid)->save() ) {
                $result = ScoreEventLogic::checkStatus($this->config, 'FillInfo');
                if ( $result['check'] and !$user['name'] ) {
                    $scoreHandle = DistributionShopScore::getInstance("FillInfo", array('cid'=>$this->cid, 'uid' => $this->uid), $result['driverConfig']);
                    $scoreHandle->exec();
                }
                $this->ajaxSuccess("保存资料成功");
	        } else {
	            $this->ajaxError("保存资料失败");
	        }
	    } else {
	        $this->ajaxError("提交失败:".$m->getError());
	    }
	}
	
	/**
	 * 首页
	 */
	public function indexAction() {
	    $this->setPageTitle($this->getShopTitle());
		$goodsLists = $this->goodsLists();
//dump($goodsLists);die;
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 搜索
	 */
	public function searchAction() {
	    /*基础栏目限制*/
	    $category = $this->getCategory();
	    $baseCate = I('baseCate', 0, 'intval') and $baseCate = M('DistributionShopCategory')->where('id=%d', $baseCate)->find();
	    if( $baseCate and in_array("$this->catId", explode(',', $baseCate['path']))) { // 小于等于基础栏目
	        $this->setCategory( $baseCate );
	    }
	    $this->ajaxReturn($this->search());
	}
	
	/**
	 * 商品分类
	 */
	public function categoryAction() {
	    $this->display();
	}
	
	/**
	 * 商品列表
	 */
	public function listAction() {
	    $this->getCategory();
	    $result = $this->search();
	    $result['baseCate'] = $this->catId;
	    $this->assign("searchList", $result);
	    $this->assign('searchListJSON', json_encode($result));
	    $this->assign("baseCate", $result['baseCate'] ); // 设置了基础栏目
	    $this->display();
	}
	
	/**
	 * 金牌会员商品
	 */
	public function dealerIndexAction() {
		$this->setPageTitle("金牌会员商品");
		$goodsLists = $this->dealerGoodsLists();
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 套餐商品
	 */
	public function agentIndexAction() {
		$this->setPageTitle("商品套餐");
		$packageLists = $this->packageLists();
		$this->assign("packageLists", $packageLists);
		$this->display();
	}
	
	/**
	 * 扩展信息
	 */
	public function configAction() {
		$id = I('id', 0, 'intval');
		$config = M('DistributionShopConfig')->where("cid=%d AND id=%d", $this->sid, $id)->find();
		$this->assign('extendConfig', $config);
		$this->display();
	}
	
	/**
	 * 获得商品套餐
	 */
	protected function packageLists() {
		return M("DistributionShopPackage")->where("cid=%d and status=1 and is_deleted=0", $this->cid)->select();
	}
	
	/**
	 * 获得金牌会员商品(金牌会员价大于0的商品)
	 */
	public function dealerGoodsLists() {
		$userRole = new UserRole();
		if ( $userRole->type($this->user['type'])->isNot(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
			header('Content-Type:text/html; charset=utf-8');
			$this->redirect('DisShop/index', array('sid'=>$this->cid), 5, "您还不是金牌会员无权查看金牌会员商品");
		}
		$goodsLists = M("DistributionShopGoods")->where(array('cid'=>$this->cid, 'is_deleted' => 0, 'status' => 1, 'dealer_price'=>array("gt", 0)))->order('sort asc,id desc')->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['attrs_cfg'] = unserialize($v['attrs_cfg']);
			$v['images'] = unserialize($v['images']);
			$v['url'] = U("DisShop/show", array('sid' => $this->cid, 'id' => $v['id'], 'mid' => $this->user['id'] ));
		}
		return $goodsLists;
	}
	
	/**
	 * 获得分销商品
	 */
	public function goodsLists(){
		//dump($this->cid);die;
		$goodsLists = M("DistributionShopGoods")->cache(true, 10)->where(array('cid'=>$this->cid, 'is_deleted' => 0, '_string' => "status=1 or (status=0 and timing_shelves!=0)"))->order('sort asc,id desc')->select();
		
		foreach ( $goodsLists as $k => &$v ) {
			$v['attrs_cfg'] = unserialize($v['attrs_cfg']);
			$v['images'] = unserialize($v['images']);
			$v['url'] = U("DisShop/show", array('sid' => $this->cid, 'id' => $v['id'], 'mid' => $this->user['id'] ));
		}
	
		return $goodsLists;
	}
	
	/**
	 * 商品详细
	 */
	public function showAction() {
		//dump($_GET);die;
		$id = I('id', 0, "intval");
		$goods = M("DistributionShopGoods")->cache(true, 10)->where("cid=%d and id=%d and is_deleted=0", $this->cid, $id)->find();
		
		// 捐赠
		if ($goods){
		    $goods['donate_money_real'] = DistributionShopDonate::getDonateMoney($this->config['donate_on'], $goods['donate_money']);
		    $goods['donate_sum'] = DistributionShopDonate::getSum(array('cid'=>$this->cid,'goodsId'=>$goods['id']));
		}
		// 定时上架
		if ( $goods ) {
		
		    if ( !$goods['status'] ) {
		        if ( $goods['timing_shelves'] and $goods['timing_shelves'] <= time() ) {
		            M("DistributionShopGoods")->save(array('id'=>$goods['id'], 'timing_shelves'=>0, 'status'=>1));
		            $goods['timing_shelves'] = 0;
		            $goods['status'] = 1;
		        }
		    }
		}
		
		if ( $goods ) {
		
		    if ( $goods['status'] ) {
		        if ( $goods['timing_ends'] and $goods['timing_ends'] <= time() ) {
		            M("DistributionShopGoods")->save(array('id'=>$goods['id'], 'timing_ends'=>0, 'status'=>0));
		            $goods['timing_ends'] = 0;
		            $goods['status'] = 0;
		        }
		    }
		}
		// 店主信息
		$currentAgent = $this->getCurrentAgent();
		if ( $currentAgent ) {
		    $this->assign("currentAgent", $currentAgent);
		}
		if ( $goods ) {
			if ( $goods['try'] ) {
				redirect(U('DisShopTry/show', "goodsId={$goods['id']}&sid={$this->sid}"));	
			}
			$goods['attrs_cfg'] = unserialize($goods['attrs_cfg']);
			$goods['images'] = unserialize($goods['images']);
			
			/* 换算城币 */
			// 购物返币
			$checkInfo = ScoreEventLogic::checkStatus($this->config, 'TradeReward');
			if ( !$checkInfo['check'] ) {
			    $goods['reward_currency'] = 0;
			}
			// 商品最大可用积币兑换
			$checkInfo = ScoreEventLogic::checkStatus($this->config, 'ScoreTrade');
			if ( $checkInfo['check'] ) {
			    if ( $goods['currency_enabled'] ) {
			        $goods['currency_value'] = ceil($goods['price']*100/$this->config['currency_config']['value']*$goods['currency_percent']/100);
			    } else {
			        $goods['currency_value'] = 0;
			    }
			}
			
			$this->setShare(array(
					'desc' => $goods['description'],
					'title' => $goods['name'],
			        'imgUrl' => $goods['image_share'],
			));
			
			$this->setPageTitle($goods['name']);
			$this->assign("shopGoods", $goods);
			$this->display();
		} else {
			$this->error('商品已不存在');
		}
	}
	
	/**
	 * 个人中心
	 */
	public function myAction() {
		$this->setPageTitle('个人中心');
		// 订单导航
		$this->getOrderNav();
		// 礼单导航
		//$this->getGiftsNav();
		// 红包导航
		$this->getRedPacketNav();
		// 用户信息
		$user = $this->getUser();
		// 分销订单数
		$user['orderCount'] =  M("DistributionShopOrder a")->join("__WECHAT_USER__ b on a.uid=b.id", "LEFT")
												->join("__DISTRIBUTION_SHOP_USER_TREE__ c on c.uid=b.id", "LEFT")
												->field("a.*,b.nickname,c.tree")
												->where(array(
														'a.order_status' => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
														'_complex' => array(
																'a.reward_uids'=>array('exp', "!='' and a.reward_uids is not null and find_in_set({$this->uid}, a.reward_uids)"), // 在参与返佣的用户之内
																'a.reward_uids_dealer'=>array('exp', "!='' and a.reward_uids_dealer is not null and find_in_set({$this->uid}, a.reward_uids_dealer)"), // 在参与返佣的用户之内
																'_logic' => 'or',
														),
												))->count();
		// 是否代理 
		$userRole = new UserRole();
		if ( $userRole->type($user['type'])->is(WechatUserModel::USER_TYPE_AGENT)  ) {
		    $this->assign("isAgent", 1);
		}
		// 是否购买过套餐商品
		$updateOrder = M("Order")->where(array("type"=>OrderModel::ORDER_TYPE_AGENT_PACKAGE, "uid"=>$this->uid))->find();
		if ( $updateOrder ) {
		    $this->assign("isBought", 1);
		}
		// 店主信息
        $currentAgent = $this->getCurrentAgent();
        if ( $currentAgent ) {
            $this->assign("currentAgent", $currentAgent);
        }
        // 结算统计
        $settleAccountsCount = $this->getSettleAccountsCount();
        $this->assign("settleAccountsCount", $settleAccountsCount);
        
		$this->assign("user", $user);
		$this->assign("backUrl", urlencode($this->getCurrentUrl()));
		$this->display();
	}
	
	/**
	 * 获得推荐的金牌会员人数(直属 间接二级 间接三级)
	 */
	public function getRecommendedDealerCountAction() {
	    $mid = array($this->uid);
	    $data = array();
	    $level = 3;
	    for ($i=0; $i<$level; $i++) {
	        $list = M("WechatUser")->where(array(
	            'cid'=>$this->cid,
	            'mid'=> array('in', $mid),
	            'type' => array('exp', "is not null and SUBSTRING(bin(type),-3,1)*1>0")
	        ))->getField("id", true);
	        $mid = $list;
	        $data[$i] = count($list);
	    }
	    $this->ajaxSuccess('', $data);
	}
	
	/**
	 * 下属金牌会员页
	 */
	public function downDealerAction() {
	    $l = I('level', 0, 'intval');
	    $mid = array($this->uid);
	    $data = array();
	    $level = 3;
	    for ($i=0; $i<$level; $i++) {
	        $list = M("WechatUser")->where(array(
	            'cid'=>$this->cid,
	            'mid'=> array('in', $mid),
	            'type' => array('exp', "is not null and SUBSTRING(bin(type),-3,1)*1>0")
	        ))->getField("id", true);
	        $mid = $list;
	        $data[$i] = M("WechatUser")->where(array('cid'=>$this->cid, 'id'=>array('in', $list)))->field("cid,face,nickname,subCount")->select();
	        if ($i >= $l) break;
	    }
	    $this->assign("level", $l);
	    $this->assign("userList", $data);
	    $this->display();
	}
	
	/**
	 * 分销佣金总量
	 * @param unknown $list
	 * @return number
	 */
	public function distributionCount( $list ) {
	     $total = 0;
	     foreach ( $list as $k => $v ) {
	        $combine = array();
	        $v['reward_uids'] and $combine = array_combine(explode(',', $v['reward_uids']), explode(',', $v['reward_bonus']));
	        $combine and $total+=$combine[$this->uid];
	        
	        $combine = array();
	        $v['reward_uids_dealer'] and $combine = array_combine(explode(',', $v['reward_uids_dealer']), explode(',', $v['reward_bonus_dealer']));
	        $combine and $total+=$combine[$this->uid];
	     }
	     return $total;
	}
	
	/**
	 * 今日、一周、一个月分销统计
	 */
	public function getDistributionCountAction() {
	    $count = array(); 
	    $condition = array(
	        'cid'=>$this->cid,
	        'pay_status' => OrderModel::PAY_STATUS_PAID,
	        '_string'=>"(find_in_set({$this->uid}, reward_uids) or find_in_set({$this->uid}, reward_uids_dealer))"
	    );
	    $daylist = M("DistributionShopOrder")->where(array_merge($condition, array(
	        'pay_time' => array('between', array(strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59')))),
	    )))->select();
	    $count[0] = $this->distributionCount($daylist);
	    
	    $daylist = M("DistributionShopOrder")->where(array_merge($condition, array(
	        'pay_time' => array('between', array('-7 days', time())),
	    )))->select();
	    $count[1] = $this->distributionCount($daylist);
	    
	    $daylist = M("DistributionShopOrder")->where(array_merge($condition, array(
	        'pay_time' => array('between', array('-30 days', time())),
	    )))->select();
	    $count[2] = $this->distributionCount($daylist);
	    $this->ajaxSuccess('', $count);
	}
	
	/**
	 * 利益结算统计
	 * @return number
	 */
	public function getSettleAccountsCount() {
	    $agent = M("Agent")->cache(true)->where("wechat_uid=%d", $this->uid)->find();
	    $orderCount = 0;
	    if ( $agent ) {
               $orderCount = M("DistributionShopOrderSettleAccounts a")->where(array('a.cid' => $this->cid, 'a.end_agent' => $agent['id']))
                                                            	    ->field("sum(a.surplus) as sumSuplus,count(a.order_id) as orderCount")
                                                                   	->find();	        
	    }
        return $orderCount;
	}
	
	/**
	 * 商家利益
	 */
	public function agentDistributionOrderAction() {
	    $agent = M("Agent")->cache(true)->where("wechat_uid=%d", $this->uid)->find();
	    $orderList = null;
	    if ( $agent ) {
	        $orderCount = $this->getSettleAccountsCount();
	        $orderList = M("DistributionShopOrderSettleAccounts a")->join("__DISTRIBUTION_SHOP_ORDER__ b on a.order_id=b.id", "LEFT")
	                                                  ->join("__WECHAT_USER__ c on c.id=b.uid", "LEFT")
	                                                  ->where(array('a.cid' => $this->cid, 'a.end_agent' => $agent['id']))
	                                                  ->field("a.surplus actualSurplus,a.status,b.order_id,b.goods_amount,b.deal_time,b.surplus,c.nickname")
	                                                  ->order("a.id desc")
	                                                  ->select();
	    }
	    $this->assign("agentDistributionOrder", $orderList);
	    $this->assign("orderCount", $orderCount);
	    $this->display();
	}
	
	/**
	 * 订单导航
	 */
	public function orderNavAction() {
	    // 用户信息
	    $user = $this->getUser();
        $this->assign("user", $user);
	    $this->getOrderNav();
	    $this->display();
	   
	}
	
	/**
	 * 我的业绩
	 */
	public function achievementAction() {
		$this->setPageTitle("我的业绩");
		$goodsLists = M("DistributionShopGoodsPromotion a")->join("__DISTRIBUTION_SHOP_GOODS__ b on a.productId = b.id", "LEFT")
													->where(array(
														'a.cid' => $this->cid,
														'a.uid' => $this->uid,
													))
													->field("a.orderCount,a.saledTotal,a.rewardsTotal,a.dealerRewardsTotal,b.name,b.price,b.images,b.id,b.reward_set,b.reward_price,b.reward_percent,b.reward_set_dealer,b.reward_price_dealer,b.reward_percent_dealer")
													->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['imageFirst'] = array_shift(unserialize($v['images']));
			$v['myBouns'] = $this->getRewardPercent( $v );
		}
		$this->assign("unpromotionCount", $this->getUnpromotionCount());
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 *  获得未推广的商品数
	 */
	private function getUnpromotionCount() {
		$sharedProductIdSql = M("DistributionShopGoodsPromotion")->where('cid=%d and uid=%d', $this->cid, $this->uid)->field('productId')->select(false);
		$condition = array(
				'cid' => $this->cid,
				'id' => array('exp', "not in $sharedProductIdSql"),
				'status' => 1,
				'is_deleted' => 0,
		);
		return M("DistributionShopGoods")->where($condition)->count();
	}
	
	/**
	 * 有佣金显示的商品列表
	 */
	public function shareGoodsAction() {
		$exceptShared = I('exc', 0); // 排除已分享过的商品
		$condition = array(
			'cid' => $this->cid,
			'status' => 1,
			'is_deleted' => 0,
		);
		$sharedProductIdSql = M("DistributionShopGoodsPromotion")->where('cid=%d', $this->cid)->field('productId')->select(false);
		$exceptShared and $condition['id'] = array('exp', "not in $sharedProductIdSql");
		$goodsLists = M("DistributionShopGoods")->where($condition)->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['imageFirst'] = array_shift(unserialize($v['images']));
			$v['myBouns'] = $this->getRewardPercent( $v );
		}
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 素材列表
	 */
	public function materialListAction() {
		$id = I('id', 0, 'intval');
		$distributionGoodsMaterialLists = M("DistributionShopGoodsMaterial")->where('cid=%d and productId=%d and status=1 and is_deleted=0', $this->cid, $id)->select();
		foreach ( $distributionGoodsMaterialLists as &$v) {
			$v['url'] = U('DisShop/showMaterial', 'sid='.$this->sid."&id=".$v['id']);
		}
		$distributionGoodsMaterialLists or $distributionGoodsMaterialLists = array();
		$distributionGoodsMaterialLists[] = array('name' => '产品详细',
												'url' => U('DisShop/show', 'sid='.$this->sid."&id=".$id));
		$this->ajaxSuccess('', $distributionGoodsMaterialLists);
	}
	
	/**
	 * 显示素材信息
	 */
	public function showMaterialAction() {
		$id = I('id', 0, 'intval'); // 素材id
		$distributionShopGoodsMaterial = M("DistributionShopGoodsMaterial a")->join('__DISTRIBUTION_SHOP_GOODS__ b on a.productId=b.id')
																			->where('a.cid=%d and a.id=%d', $this->cid, $id)
																			->field('a.*')->find();
		$distributionShopGoodsMaterial['url'] = U('DisShop/show', "sid={$this->sid}&id={$distributionShopGoodsMaterial['productId']}");
		$this->setPageTitle($distributionShopGoodsMaterial['title']);
		$this->assign("distributionShopGoodsMaterial", $distributionShopGoodsMaterial);
		$this->setShare(array(
			'desc' => $distributionShopGoodsMaterial['description'],
			'title' => $distributionShopGoodsMaterial['title'],
		));
		$this->display();	
	}
	
	/**
	 * 我的下线客户
	 */
	public function myCustAction() {
		$userList = M("WechatUser")->where(array('mid' => $this->uid, 'cid' => $this->cid))->field('*,1 as level')->select();
		$this->assign("userList", $userList);
		$this->display();
	}
	
	/**
	 * 下线客户异步请求
	 */
	public function downCustAction() {
		$mid = I('fid', $this->uid, 'intval');
		$wechatUserList = M("WechatUser a")->join("__DISTRIBUTION_SHOP_USER_TREE__ b on a.id=b.uid")->where(array('a.mid' => $mid, 'a.cid' => $this->cid))->field('a.*,b.tree')->select();
		foreach ( $wechatUserList as &$v) {
			$v['level'] = $this->getLevel($this->uid, $v['tree']);
		}
		$this->ajaxSuccess('', $wechatUserList);
	}
	
	/**
	 * 我的分销订单
	 */
	public function disOrderAction() {
	    $rewardNames = array(1=>'销售积分',2=>'渠道积分',3=>'返单积分');
		$orderLists = M("DistributionShopOrder a")->join("__WECHAT_USER__ b on a.uid=b.id", "LEFT")
							  ->join("__DISTRIBUTION_SHOP_USER_TREE__ c on c.uid=b.id", "LEFT")
							  ->field("a.*,b.nickname,c.tree")
							  ->where(array(
							  		'a.cid' => $this->cid,
							  		'a.order_status' => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
							  		'_complex' => array(
							  			'a.reward_uids'=>array('exp', "!='' and a.reward_uids is not null and find_in_set({$this->uid}, a.reward_uids)"), // 在参与返佣的用户之内
							  			'a.reward_uids_dealer'=>array('exp', "!='' and a.reward_uids_dealer is not null and find_in_set({$this->uid}, a.reward_uids_dealer)"), // 在参与返佣的用户之内
							  			'_logic' => 'or',
								  	),
								))->select();
		foreach ( $orderLists as &$v ) {
			$v['all_rewards'] = array_combine(explode(',', $v['reward_uids']), explode(',', $v['reward_bonus']));
			$vDealerBouns = array_combine(explode(',', $v['reward_uids_dealer']), explode(',', $v['reward_bonus_dealer']));
			foreach ( $vDealerBouns as $k => $bonus ) {
				$v['all_rewards'][$k] += $bonus;
			}
			$v['my_rewards'] = $v['all_rewards'][$this->uid];
			$v['level'] = $this->getLevel($this->uid, $v['tree']);
			$v['reward_name'] = $rewardNames[$v['level']];
		}
		$this->assign("orderLists", $orderLists);
		$this->display();
	}
	
	/**
	 * 我的奖金(积分)
	 */
	public function myBonusAction() {
		$user = $this->getUser();
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
	 * 提现页
	 */
	public function withdrawAction() {
		$this->setPageTitle("提现申请");
		$user = $this->getUser();
		$defaultBank = $this->getDefaultBank();
		$user['defaultBank'] = $defaultBank;
		$this->assign("backUrl", urlencode($this->getCurrentUrl()));
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
	 * 提现记录
	 */
	public function withdrawRecordAction() {
		$withdrawRecord = M("DistributionShopUserWithdraw")->where("cid=%d and uid=%d", $this->cid, $this->uid)->order('createTime desc')->select();
		$this->assign("withdrawRecord", $withdrawRecord);
		$this->display();
	}
	
	/**
	 * 提现提交
	 */
	public function withdrawPostAction() {
		function getmicrotime($e = 7) {
			list($u, $s) = explode(' ',microtime());
			return bcadd($u, $s, $e);
		}
		// 默认支付银行
		$defaultUserBankId = I("defaultUserBankId", 0, "intval");
		$distributionShopUserBank = M("DistributionShopUserBank a")->join("__BANK__ b on a.bankId=b.id", "LEFT")->where("a.id=%d", $defaultUserBankId)->field("a.*,b.name as bankName")->find();
		if ( empty($distributionShopUserBank) ) {
			$this->ajaxError('未选择支付的银行');
		}
		// 记录提现
		$no = str_replace('.', '', getmicrotime()).rand(100, 999).$this->uid ;
		$m = M("DistributionShopUserWithdraw");
		if ( $m->create() ) {
			$m->cid = $this->cid;
			$m->uid = $this->uid;
			$m->status = 0;
			$m->createTime = time();
			$m->no = $no;
			$m->bankName = $distributionShopUserBank['bankName'];
			$m->accountName = $distributionShopUserBank['accountName'];
			$m->account = $distributionShopUserBank['account'];
			$user = $this->getUser();
			$minWithdraw = $this->config['min_withdraw'];
			if ( $user['withdrawable']*1 and ($user['withdrawable']*1 >= $m->money*1 ) ) {
				if ( $minWithdraw and $minWithdraw*1 > $m->money*1 ) {  // 判断提现金额是否达到最低提现标准
					$this->ajaxError('提现金额至少为:'.$minWithdraw);
				}
				if ( $m->add() ) {
					$this->ajaxSuccess('提现申请成功');
				} else {
					$this->ajaxError('提现申请失败');
				}
			} else {
				$this->ajaxError('输入的积分超出了可提积分');
			}
		}
		$this->ajaxError($m->getError());
	}
	
	/**
	 * 添加收款银行
	 */
	public function addBankAction() {
		C("TOKEN_ON", false);
		$bank = array();
		$banks = M("Bank")->getField('id,name');
		$bank['provinceOptions'] = $this->getOption(Region::getProvinceList(), $bank['province'], '==请选择省份==');
		$bank['cityOptions'] = $this->getOption(Region::getCityListByProvince($bank['province']), $bank['city'], '==请选择城市==');
		$bank['bankOptions'] = $this->getOption($banks);
		$this->assign("bank", $bank);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display("saveBank");
	}
	
	/**
	 * 解除绑定银行卡
	 */
	public function delectBankAction() {
// dump($_GET);die;
		if($_GET['sid']){
			
			$bankLists = M("DistributionShopUserBank")->where(array('cid'=>$_GET['sid']))->delete();
				if($bankLists){
					$this->success('解绑成功',U('DisShop/my', array('sid'=>$this->cid, 'id' => $v['id'])));
					exit;
				}else{
					$this->error('解绑失败',U('DisShop/my', array('sid'=>$this->cid, 'id' => $v['id'])));
					exit;
				}
			}
	
		}
	
	/**
	 * 保存收款银行
	 */
	public function modifyBankAction() {
		C("TOKEN_ON", false);
		$id = I('id', 0, 'intval');
		$m = M("DistributionShopUserBank");
		$bank = $m->where('id=%d and uid=%d', $id, $this->uid)->find();
		$banks = M("Bank")->getField('id,name');
		$bank['provinceOptions'] = $this->getOption(Region::getProvinceList(), $bank['province'], '==请选择省份==');
		$bank['cityOptions'] = $this->getOption(Region::getCityListByProvince($bank['province']), $bank['city'], '==请选择城市==');
		$bank['bankOptions'] = $this->getOption($banks);
		$this->assign("bank", $bank);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display("saveBank");
	}
	
	/**
	 * 银行列表
	 */
	public function myBankListAction() {
		$bankLists = M("DistributionShopUserBank a")->join("__BANK__ b on a.bankId=b.id", "LEFT")->where("a.cid=%d and a.uid=%d", $this->cid, $this->uid)
												->field("a.*,b.name as bankName")->order('isDefault desc')->select();
								//dump($bankLists);die;
		foreach ($bankLists as &$v) {
			$v['lastCode'] = substr($v['account'], -4);
		}
		$this->assign("bankLists", $bankLists);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display();
	}
	
	/**
	 * 保存银行
	 */
	public function saveBankAction() {
		C("TOKEN_ON", false);
		$m = M("DistributionShopUserBank");
		if ( $m->create() ) {
			$m->cid = $this->cid;
			$m->uid = $this->uid;
			if ( empty($m->id) ) {
				unset($m->id);
				$m->isDefault = 1;
				$id = $m->add();
				if ( $id ) {
					$m->where(array('id' => array('neq', $id), 'uid' => $this->uid))->setField("isDefault", 0);
					$this->ajaxSuccess("添加成功");
				} else {
					$this->ajaxSuccess("添加失败");
				}
			} else {
				if ( false !== $m->where('id=%d', $this->id)->save() ) {
					$this->ajaxSuccess("修改成功");
				} else {
					$this->ajaxError("修改失败");
				}
			}
		}
		$this->ajaxError($m->getError());
	}
	
	/**
	 * 获取城市
	 */
	public function getCityPostAction() {
		echo $this->getOption(Region::getCityListByProvince(I('code')), '', '==请选择城市==');
	}
	
	/**
	 * 设置默认银行
	 */
	public function setDefaultBankAction() {
		$id = I('bankId', 0, "intval");
		$m = M("DistributionShopUserBank");
		if ( false !== $m->where(array('uid' => $this->uid))->save(array('isDefault' => array('exp', "CASE id WHEN $id THEN 1 ELSE 0 END"))) ) {
			$this->ajaxSuccess('设置成功');
		} else {
			$this->ajaxSuccess('设置失败');
		}
	}
	
	/**
	 * 公益项目列表
	 */
	public function donateProjectListsAction(){
	    $this->itemLists = DistributionShopDonate::getDonateProjectLists($this->cid,true);
	    $this->display();
	}
	
	/**
	 * 获得用户级别
	 * @param unknown $id 根级id
	 * @param unknown $tree tree字符串
	 * @return number
	 */
	private function getLevel($id, $tree) {
		$i = 0;
		$treeAttr = explode(',', $tree);
		foreach ( $treeAttr as $v ) {
			if ( $v != $id ) {
				$i++;
			} else {
				break;
			}
		}
		return $i;
	}
	
	/**
	 * 积分记录
	 */
	public function scoreRecordAction() {
	   $scoreList = M("DistributionShopScoreRecord")->where("cid=%d and uid=%d", $this->cid, $this->uid)->order("create_time desc")->select();
	   $this->assign("scoreList", $scoreList);
	   $this->display();
	}
	
	/**
	 * 获得商户标题
	 */
	public function getShopTitle() {
	    if ( $this->config['agent_shop_config'] and $this->config['agent_shop_config']['show_agent_name'] ) {
	        $agentList = $this->getParentAgentList();
	        if ( $agentList ) {
	            return $agentList[0]['name'];
	        }
	    }
	    return $this->config['name'];
	}
	
	/**
	 * 联系我们
	 */
	public function concatAction() {
	    $agentList = $this->getParentAgentList();
	    $this->assign("agentList", $agentList);
	    $this->display();
	}
	
	/**
	 * 获得我的代理商
	 */
	private function getParentAgentList() {
	    if ( $this->aid )  {
	        $agent = M("Agent")->cache(true)->where(array('cid'=>$this->cid, 'id'=>$this->aid))->find();
	        $agentList[] = $agent;
	    }
	    return $agentList;
	}
	
	/**
	 * 获得代理推荐列表数组
	 * @return multitype:unknown
	 */
	private function getAgentList() {
	    $user = $this->getUser();
	    $userRole = new UserRole();
	    $agentList = array();
	    $parentId = 0;
	    if ( $userRole->type($user['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 购买者是代理商
	        $agent = M("Agent")->cache(true)->where(array('cid'=>$this->cid, 'wechat_uid'=>$this->uid))->find();
	        $agentList[] = $agent;
	        $parentId = $agent['parent_id'];
	    } elseif ( $this->aid )  {
	        $agent = M("Agent")->cache(true)->where(array('cid'=>$this->cid, 'id'=>$this->aid))->find();
	        $agentList[] = $agent;
	        $parentId = $agent['parent_id'];
	    }
	    while ( $parentId ) {
	        $agent = M("Agent")->cache(true)->where(array('cid'=>$this->cid, 'id'=>$parentId))->find();
	        if ( $agent ) {
	            $agentList[] = $agent;
	        }
	        $parentId = $agent['parent_id'];
	    }
	    return $agentList;
	}
	
	/**
	 * 获得默认银行
	 * @return string
	 */
	private function getDefaultBank() {
		$userBank = M("DistributionShopUserBank a")->where(array(
			'a.cid' => $this->cid,
			'a.uid' => $this->uid,
		))->join("__BANK__ b on a.bankId=b.id", "LEFT")->field("a.*,b.name as bankName")->order('a.isDefault desc')->limit(1)->find();
		$userBank and $userBank['lastCode'] = substr($userBank['account'], -4);
		return $userBank;
	}
	
	/**
	 * 获得用户提现信息
	 * @return Ambigous <number, string>
	 */
	private function getUser() {
		// 用户信息
		$user = M("WechatUser")->find($this->uid);
		// 可提现
		$money = M("DistributionShopUserWithdraw")->where("uid=%d and status=0", $this->uid)->sum('money'); // 授理中的提现
		$minWithdraw = $this->config['min_withdraw'];
		$withdrawable = $user['bonus']*1 - $user['mention']*1 - $money; // 总收入  - 已提 - 在提 = 可提
		if ( $withdrawable < $minWithdraw ) { // 判断余额是否达到最低提现标准
			$user['withdrawable'] = 0;
		} else {
			$user['withdrawable'] = $withdrawable; // number_format($withdrawable, 2);
		}
		$user["typeName"] = WechatUserModel::getUserTypeName($user['type'], $this->cid, $user['id']);
		$user['engagedInMoney'] = $money;
		// 积分
		if ( $this->config['currency_config']['opened'] ) {
		    $scoreHandle = DistributionShopScore::getInstance("TradeReward", array('cid'=>$this->cid, 'uid' => $this->uid));
		    $userScore = $scoreHandle->getEnabledScore();
		    $user['userEnableScore'] = $userScore*1;
		}
		return $user;
	}
	
	/**
	 * 送礼导航
	 */
	private function getGiftsNav() {
		$types = array();
		foreach (DistributionShopOrderModel::$GIFTS_TYPES as $type => $v) {
			$condition = array(
					"orders.uid" => $this->uid,
					"orders.cid" => $this->sid,
					"orders.buy_method" => DistributionShopOrderModel::BUY_METHOD_GIFTS,
			);
			if ( $type == 1 ) { // 我的送礼 
				
			} elseif( $type == 2 ) { // 我的收礼
				unset($condition['orders.uid']);
				$condition['gifts.to_uid'] = $this->uid;
			}
			$count = M("DistributionShopOrder orders")->join ( "__DISTRIBUTION_SHOP_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" )->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("giftsTypes", $types);
	}
	
	/**
	 * 红包导航
	 */
	private function getRedPacketNav() {
		$types = array();
		foreach (DistributionShopRedPacketModel::$EFFICACYS_NAV as $type => $v) {
			$condition = array(
					"packet.uid" => $this->uid,
					"packet.cid" => $this->sid,
					"packet.efficacy" => $type,
					"packet.endTime" => array('exp', "=0 or packet.endTime>unix_timestamp()"),
			);
			$count = M("DistributionShopRedPacket packet")->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("redPacketTypes", $types);
	}
	
	/**
	 * 订单导航
	 */
	private function getOrderNav() {
		$types = array();
		foreach (DistributionShopOrderModel::$TYPES as $type => $v) {
			$d = M("DistributionShopOrder orders");
			$condition = array(
				"orders.uid" => $this->uid,
				"orders.cid" => $this->sid,
		        "orders.is_deleted" => 0,
			);
			if ($type == 1) { // 未付款
				$condition['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_PAY;
			} else if ($type == 2) { // 待签收(已付款,货到付款)
				$condition['orders.order_status'] = array(
						"in",
						array(
								DistributionShopOrderModel::ORDER_STATUS_SHIPPING,
								DistributionShopOrderModel::ORDER_STATUS_SIGN
						)
				);
				unset( $condition['orders.uid'] ); 
				/* 我的待收货订单与 收礼订单 */
				$d->join ( "__DISTRIBUTION_SHOP_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" );
				$condition['orders.id'] = array('exp', "is not null and (
													((gifts.to_uid=0 or gifts.to_uid is null) and orders.uid={$this->uid}) 
														or 
													(gifts.to_uid={$this->uid})
												)");
			} else if ($type == 3) { // 交易成功
				$condition['orders.order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
			} else if ($type == 4) { // 退款订单
				$condition['orders.refund_times'] = array('gt', 0);
			} else { // 其它
				$condition['orders.order_status'] = array(
						"not in",
						array(
								DistributionShopOrderModel::ORDER_STATUS_PAY,
								DistributionShopOrderModel::ORDER_STATUS_SHIPPING,
								DistributionShopOrderModel::ORDER_STATUS_SIGN,
								DistributionShopOrderModel::ORDER_STATUS_COMPLETED
						)
				);
			}
			$count = $d->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("types", $types);
	}
	
	private function getRewardPercent( $shopGoods ) {
		/* 基础分成比例 */
		$rewardPrice = $shopGoods['reward_price']; // 特约经销商佣金
		$rewardPercent = array();
		$bonus = array();
		if ( $shopGoods['reward_set'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent'] and $rewardPercent = explode(':', $shopGoods['reward_percent']);
		} else { // 系统默认分成比例
			$this->config['reward_percent'] and $rewardPercent = explode(':', $this->config['reward_percent']);
		}
		foreach ( $rewardPercent as $v ) {
			$bonus[] = $v/100*$rewardPrice."(基础)";
		}
		$userRole = new UserRole();
		if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
			/* 特约经销商佣金发放比例 */
			$rewardPriceDealer = $shopGoods['reward_price_dealer']; // 特约经销商佣金
			$rewardPercentDealer = array();
			/* 特约经销商分成比例  */
			if ( $shopGoods['reward_set_dealer'] ) { // 商品设置的分成比例
				$shopGoods['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $shopGoods['reward_percent_dealer']);
			} else { // 系统默认分成比例
				$this->config['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $this->config['reward_percent_dealer']);
			}
			$i = 0;
			foreach ( $rewardPercentDealer as $v ) {
				$bonus[$i] = $bonus[$i].($bonus[$i]?"+":"").'￥'.($v/100*$rewardPriceDealer)."(特销商)";
				$i++;
			}
		}
		return $bonus[0]?$bonus[0]:'无佣金';
	}
}